package com.feihao.zhou.demo01;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectGetFiled {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        /*Class clazz = Class.forName("com.feihao.zhou.demo01.Student");

        //获取所有非私有成员变量：
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        System.out.println("--------------------");
        //获取所有成员变量：
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        System.out.println("--------------------");

        //获取单个指定名称的成员变量：
        Field sex = clazz.getField("sex");
        System.out.println(sex);

        System.out.println("--------------------");

        //获取单个私有的成员变量
      *//*  Field name = clazz.getField("name");    //报错！！！
        System.out.println(name);*//*

        Field name = clazz.getDeclaredField("name");
        System.out.println(name);
        name.setAccessible(true);  //解除私有成员变量的访问检查

        Student student = (Student) clazz.newInstance();   //创建对象,为私有变量进行赋值
        name.set(student,"7788");  //赋值  ,参数一:对象,  参数二:要赋值 的参数

        System.out.println(student);*/

        //获取Class对象：
        Class<?> aClass = Class.forName("com.feihao.zhou.demo01.Student");
        Field[] declaredFields = aClass.getDeclaredFields();  //获取所有成员变量”
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        //获取私有成员变量并赋值：
        Field age = aClass.getDeclaredField("age");
        age.setAccessible(true);//取消安全检查
        //创建对象，并设置值：
        Student student = (Student) aClass.newInstance();
        age.set(student,7452852);
        System.out.println(student);



    }
}
